package com.helen.ui.address;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.entity.JsonBean;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.utils.AssetsFileUtils;
import com.helen.utils.KeybordUtils;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/26.
 * 新增地址
 */

public class AddNewAddressActivity extends BaseActivity {

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }else {
                        mMProgressDialog.dismiss();
                        showPickerView();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    mMProgressDialog.dismiss();
                    showPickerView();
                    break;

                case MSG_LOAD_FAILED:
                    mMProgressDialog.dismiss();
                    break;
            }
        }
    };

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    @BindView(R.id.et_name)
    MyEditText etName;
    @BindView(R.id.et_contact)
    MyEditText etContact;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_select_location)
    LinearLayout llSelectLocation;
    @BindView(R.id.et_detail_address)
    MyEditText etDetailAddress;
    @BindView(R.id.cb)
    CheckBox cb;
    @BindView(R.id.tv_save)
    SuperTextView tvSave;
    private AddressListEntity addressListEntity;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_add_new_address;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        addressListEntity = (AddressListEntity) getIntent().getSerializableExtra("addressListEntity");
        if (addressListEntity != null) {
            getToolbarTitle().setText(R.string.edit_address);
            etName.setText(addressListEntity.getName());
            etName.setSelection(etName.getText().toString().length());
            etContact.setText(addressListEntity.getPhone());
            tvLocation.setText(addressListEntity.getCity());
            etDetailAddress.setText(addressListEntity.getDetail());
            cb.setChecked(addressListEntity.getIsDefault().equals("1") ? true : false);
        } else {
            getToolbarTitle().setText(R.string.new_address);
        }

    }

    @Override
    protected void updateViews() {

    }

    private void addAddressApi(String name, String phone, String city, String detail, String isDefault) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        if (addressListEntity != null) {
            params.put("id", addressListEntity.getId());
        }
        params.put("userid", UserHelper.getInstance().getloginEntity(AddNewAddressActivity.this).getId() + "");
        params.put("name", name);
        params.put("phone", phone);
        params.put("city", city);
        params.put("detail", detail);
        params.put("isDefault", isDefault);
        EasyHttp.post(addressListEntity == null ? Constants.API_JSONAPI_ADDADDRESS : Constants.API_JSONAPI_UPDATEADDRESS)
                .params(params)
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "新增地址失败==" + e.toString());
                        MToast.makeTextShort(AddNewAddressActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(AddNewAddressActivity.this, result, TAG);
                        if (data != null) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                });
    }


    @OnClick({R.id.ll_select_location, R.id.cb, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_location:
                if (KeybordUtils.isSoftShowing(AddNewAddressActivity.this)) {
                    KeybordUtils.closeKeybord(etContact, AddNewAddressActivity.this);
                }
                mMProgressDialog.show();
                mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                break;
            case R.id.cb:
                break;
            case R.id.tv_save:
                String name = etName.getText().toString().trim();
                String phone = etContact.getText().toString().trim();
                String city = tvLocation.getText().toString().trim();
                String detail = etDetailAddress.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    MToast.makeTextLong(AddNewAddressActivity.this, "姓名不能为空").show();
                    etName.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    MToast.makeTextLong(AddNewAddressActivity.this, "联系方式不能为空").show();
                    etContact.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(city)) {
                    MToast.makeTextLong(AddNewAddressActivity.this, "地区不能为空").show();
                    return;
                }
                if (TextUtils.isEmpty(detail)) {
                    MToast.makeTextLong(AddNewAddressActivity.this, "详细地址不能为空").show();
                    etDetailAddress.requestFocus();
                    return;
                }
                addAddressApi(name, phone, city, detail, cb.isChecked() ? "1" : "0");
                break;
        }
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                tvLocation.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new AssetsFileUtils().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

}
